import Watcher from './watcher.js'

export default {
  text(node, value, vm) {
    let result
    if (value.includes('{{')) {
      // {{}}
      result = value.replace(/\{\{(.+)\}\}/g, (...args)=>{
        const key = args[1]
        console.log('key ===', key )
        new Watcher(key, vm, (newVal)=>{
          this.textUpdater(node, newVal)
        })
        return this.getValue(key, vm)
      })
    } else {
      // v-text
      new Watcher(value, vm, (newVal)=>{
        this.textUpdater(node, newVal)
      })
      result = this.getValue(value, vm)
    }
    this.textUpdater(node, result)
  },
  on(node, value, vm) {
    const fn = vm.$methods[value]
    node.addEventListener('click', fn.bind(vm))
  },
  model(node, value, vm) {
    const that = this
    const val = this.getValue(value,vm)
    new Watcher(value, vm, (newVal)=>{
      this.modelUpdater(node, newVal)
    })
    node.addEventListener('input', function (e) {
      const newVal = e.target.value
      that.setValue(value, vm, newVal)
    })
    this.modelUpdater(node, val)
  },
  textUpdater(node, val) {
    node.textContent = val
  },
  getValue(key, vm) {
    return vm.$data[key.trim()]
  },
  setValue(key, vm, newVal) {
    vm.$data[key] = newVal
  },
  modelUpdater(node,val){
    node.value = val
  }
}